'''
Created on 09-05-05

@author: peterd
'''

from __future__ import division
import math


def getDistanceOnUnitSphere(lat1, long1, lat2, long2, unit = 'km'):
	# Convert latitude and longitude to     
	# spherical coordinates in radians.    
	degrees_to_radians = math.pi/180.0
	
	
	# phi = 90 - latitude    
	phi1 = (90.0 - lat1)*degrees_to_radians    
	phi2 = (90.0 - lat2)*degrees_to_radians
	
	# theta = longitude    
	theta1 = long1*degrees_to_radians    
	theta2 = long2*degrees_to_radians
	
	cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + \
		  math.cos(phi1)*math.cos(phi2))    
		
	arc = math.acos( cos )
	
	if unit == 'km':
		arc = arc * 6373
	elif unit == 'miles':
		arc = arc * 3960
	elif unit == 'm':
		arc = arc * 6373 * 1000

	return arc


class BoundingBox:
	def __init__(self, north, west, south, east):
		self.north_ = north
		self.west_ = west
		self.south_ = south
		self.east_ = east
		
		
	def north(self):
		return self.north_

		
	def west(self):
		return self.west_


	def south(self):
		return self.south_


	def east(self):
		return self.east_




		
def getBoundingBox(lat, long, radius):
#def getBoundingBox(lat, long, distance, unit = 'km'):
	"""For a given lat, long and distance, get the bounding box"""

	distance = radius.toM()	
	#if unit == 'km':
		#distance = distance * 1000

	lat_rad = lat / 360.0 * 2.0 * math.pi
	long_rad = long / 360.0 * 2.0 * math.pi

	# Calculate how far the distance is in lat+long
	# Values should be as right as possible, whilst being compatible
	#  with the answers from geo_helper.calculate_distance_and_bearing(

	deg_lat_km = 110.574235
	deg_long_km = 110.572833 * math.cos(lat_rad)
	#deg_lat_km = 111.133 - 0.559*math.cos(2.0*lat_rad)
	delta_lat = distance / 1000.0 / deg_lat_km
	delta_long = distance / 1000.0 / deg_long_km

	# Compute the min+max lat+long
	min_lat = lat - delta_lat
	min_long = long - delta_long
	max_lat = lat + delta_lat
	max_long = long + delta_long

	return BoundingBox(min_lat,min_long,max_lat,max_long)



class LatLng:
	def __init__(self, lat, lng):
		self.lat_ = lat
		self.lng_ = lng
		
	
	def getLat(self):
		return self.lat_


	def getLng(self):
		return self.lng_


	def getLatLng(self):
		return '%s,%s' % (self.lat_, self.lng_)        